package com.sztx.pay.center.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.sztx.commons.httpclient.HttpClientConfigBuilder;
import com.sztx.commons.httpclient.HttpClientUtil;
import com.sztx.commons.httpclient.HttpHeaderBuilder;

public class CreatAct {
	private static final Logger logger = LoggerFactory.getLogger(CreatAct.class);	
	private static final Logger grayUserlogger = LoggerFactory.getLogger("grayUserlogger");

	public static String CREATE_ACT_URL = "http://cashier.berbon.com/account/createAct?userId=%s&userType=%s";
	public static String SESSION_USER_URL = "http://cms.berbon.com/support/channel/getGroupList?d=%7b%22pageNo%22%3a1%2c%22pageSize%22%3a1%7d";
	
	public static String SYNC_BANLANCE_URL = "http://cashier.berbon.com/account/syncUserBalance?userId=";
		
	public static void main(String[] args) throws IOException, InterruptedException {
		
		BufferedReader bf = new BufferedReader(new FileReader("E:/文档/支付需要处理生成账户的帐号数据-生成缴费帐号-同步余额-修改灰度状态.txt"));
		
		Set<String> unGrayUserSet = new HashSet<String>();
		List<String> unGrayUserList = FileUtils.readLines(new File("E:/文档/aaa.txt"));
		if (unGrayUserList != null && !unGrayUserList.isEmpty()) {
			for (String userId : unGrayUserList) {
				unGrayUserSet.add(userId.trim());
			}
		}
		
		
		String readLine = null;
		int i = 1;
		long lastVisitTime = 0;
		List<String> errUserIds = new ArrayList<String>();
		while ((readLine = bf.readLine()) != null) {// 使用readLine方法，一次读一行			
			long currentTime = System.currentTimeMillis();
			if (currentTime - lastVisitTime > 60000) {  //5分钟访问一次session								
				String result = getHtmlContent(SESSION_USER_URL);				
				if (result == null || !result.startsWith("{\"code\":\"J000000\"")) { //session未访问成功
					logger.info("访问session结果失败{}", result);
					System.exit(0);
				}				
				lastVisitTime = currentTime;
			}
			
			readLine = readLine.trim();
			i++;
			
			if (unGrayUserSet.contains(readLine)) {
				grayUserlogger.warn("用户{}不灰度",readLine);
				continue;
			}			
			String[] arr = readLine.split("\\|");
			String userId = arr[1];
			String userTypeStr =  arr[2];
			Integer userType = Integer.parseInt(userTypeStr);
			Integer grayState = Integer.parseInt(arr[3]);
			if(grayState != 1){
				grayUserlogger.warn("用户{}未灰度",readLine);
				continue;
			}
//			if((userType & 8) == 0){
//				userType += 8;
//			}
			userType += 8;
			
			String url = String.format(CREATE_ACT_URL, userId,userType);	
			String syncBanlanceUrl = SYNC_BANLANCE_URL+userId;
			String result = getHtmlContent(url);
			String code = null;
			JSONObject parseObject = null;
			if (result != null && !result.isEmpty()) {
				parseObject = JSONObject.parseObject(result);
				code = parseObject.getString("code");
			}			
			
			String resultMsg = "【成功】";
			if ("J000997".equals(code)) {
				String errMsg = parseObject.getString("description");
				grayUserlogger.error("迁移第{}用户{}失败,失败原因{}", i, readLine, errMsg);
			}else {
				grayUserlogger.info("迁移第:" + i + "行,账号【" + readLine + "】," + resultMsg);				
			}
			
			
			result = getHtmlContent(syncBanlanceUrl);
			if (result != null && !result.isEmpty()) {
				try {
					parseObject = JSONObject.parseObject(result);
					code = parseObject.getString("code");
					resultMsg = "【成功】";
					if ("J000997".equals(code)) {
						errUserIds.add(userId);
						String errMsg = parseObject.getString("description");
						grayUserlogger.error("同步余额第{}用户{}失败,失败原因{}", i, readLine, errMsg);
					}else {
						grayUserlogger.info("同步余额第:" + i + "行,账号【" + readLine + "】," + resultMsg);				
					}
				} catch (Exception e) {
					grayUserlogger.error("同步余额第{}用户{}失败", i, readLine);
					errUserIds.add(userId);
				}
			}			
			
			
			//Thread.sleep(1000l);
		
		}
		grayUserlogger.info("迁移失败用户列表:" + JSONObject.toJSONString(errUserIds));
		
	}
	
	
	private static String getHtmlContent(String url){		
		HttpClientConfigBuilder clientBuilder = HttpClientConfigBuilder.custom();
		HttpHeaderBuilder headerBuilder = HttpHeaderBuilder.custom().cookie("berbonjsessionid=F78E8121E5A342F79FF76F9744A2DAD1");		
		String encoding = "UTF-8";
		return HttpClientUtil.get(clientBuilder, url, headerBuilder, encoding);	
	}
	
	
	
}
